package com.ssm.zy.handler;

import com.ssm.zy.common.SessionBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author 郑智辰~
 * @version 1.0
 *
 * WebSocket “多人聊天” 处理程序
 */
@Slf4j
@Component
public class WebSocketMultipleChatHandler extends AbstractWebSocketHandler {
    //连接池对象
    private static Map<String, SessionBean> WSConnectionPool;
    //连接对象ID
    private static AtomicInteger clientId;
    //通讯消息
    private static StringBuffer clientMessage;
    static {
        WSConnectionPool = new ConcurrentHashMap<String, SessionBean>();
        clientId = new AtomicInteger(0);
        clientMessage = new StringBuffer();
    }

    //建立连接
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        super.afterConnectionEstablished(session);
        // TODO 建立连接之后,往连接池中添加用户数据
        SessionBean sessionBean = new SessionBean(session,clientId.getAndIncrement());
        WSConnectionPool.put(session.getId(), sessionBean);
        //1.打印日志信息
        log.info(WSConnectionPool.get(session.getId()).getClientId() + "已完成连接！");
        //2.配置通知信息
        clientMessage.append(WSConnectionPool.get(session.getId()).getClientId() + "已上线！<br/>");
        //3.将消息发送给其他在线用户
        this.sendMessage(WSConnectionPool);
    }

    //收到消息并处理
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        super.handleTextMessage(session, message);
        //1.打印用户传输的信息
        log.info(WSConnectionPool.get(session.getId()).getClientId() + ":" + message.getPayload());
        //2.配置通知信息
        clientMessage.append(WSConnectionPool.get(session.getId()).getClientId() + ":" +message.getPayload() + "<br/>");
        //3.将消息发送给其他在线用户
        this.sendMessage(WSConnectionPool);
    }

    //传输发生异常时
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        super.handleTransportError(session, exception);
        if (session.isOpen()){
            session.close();
        }
        //打印消息日志
        log.error(WSConnectionPool.get(session.getId()).getClientId() + "发生异常,已断开连接！");
        //删除连接池对象
        WSConnectionPool.remove(session.getId());
    }

    //连接断开时
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        super.afterConnectionClosed(session, status);
        Integer clientId = WSConnectionPool.get(session.getId()).getClientId();
        //TODO 断开连接，删除连接池对象
        WSConnectionPool.remove(session.getId());
        //1.打印消息日志
        log.error(clientId + "已断开连接！");
        //2.拼接客户端消息
        clientMessage.append(clientId + "已断开连接！<br/>");
        //4.通知所有在线的用户
        this.sendMessage(WSConnectionPool);
    }

    //通知所有在线的用户
    public void sendMessage(Map<String,SessionBean> pool){
        for (String sessionId : pool.keySet()){
            try {
                pool.get(sessionId).getSession()
                        .sendMessage(new TextMessage(clientMessage.toString()));
            } catch (IOException e) {
                log.error(e.getMessage());
            }
        }
    }
}
